import TjTable from '@/pages/ETrade/components/TjTable';
import { TjForm, TjSlideSelect } from '@/tjComponents';
import { Form, InputNumber, message, Select, TimePicker } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import React, { useState, useEffect } from 'react';
import moment from 'moment';
import type { ArtColumn } from 'ali-react-table';
import './index.less';
import { formDataToArr } from '@/utils/editorTable';
import SingleRangePicker from '../SingleRangePicker';
import { saveDailyRollingTradeReport } from '../../services';
import { HttpCode } from '#/utils/contacts.js';
import { changeTradeTypeFn } from '../../utils';
import _ from 'lodash';

const columns: ArtColumn[] = [
  {
    name: '虚拟时段',
    width: 100,
    align: 'center',
    code: 'virtualTimeOrder',
  },
  {
    name: '时段类型',
    code: 'timeOrder',
    align: 'center',
  },
  {
    name: '买方最低限价',
    code: 'buyLowPrice',
    align: 'center',
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`buyLowPrice@${row.id}`}>
          <InputNumber min={0} disabled={row.tradeType === 1} />
        </Form.Item>
      );
    },
  },
  {
    name: '卖方最高限价',
    code: 'sellUpPrice',
    align: 'center',
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`sellUpPrice@${row.id}`}>
          <InputNumber min={0} disabled={row.tradeType === 2} />
        </Form.Item>
      );
    },
  },
  {
    name: '交易方向',
    code: 'tradeType',
    align: 'center',
    width: 100,
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`tradeType@${row.id}`}>
          <TjSlideSelect
            items={[
              { label: '买入', value: 1 },
              { label: '卖出', value: 2 },
            ]}
            // onChange={(val) => {
            //   debugger;
            //   row.tradeType = val;
            // }}
          />
        </Form.Item>
      );
    },
  },
  {
    name: '日电量',
    code: 'declarationQuantity',
    align: 'center',
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`declarationQuantity@${row.id}`}>
          <InputNumber min={0} />
        </Form.Item>
      );
    },
  },
  // {
  //   name: '交易电价',
  //   code: 'declarationPrice',
  //   align: 'center',
  //   // width: 150,
  //   render: (value: any, row: any) => {
  //     return (
  //       <Form.Item name={`declarationPrice@${row.id}`}>
  //         <InputNumber min={0} />
  //       </Form.Item>
  //     );
  //   },
  // },
  {
    name: '交易时间',
    code: 'times',
    align: 'center',
    width: 200,
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`times@${row.id}`}>
          <TimePicker.RangePicker format={'HH:mm'} allowClear={false} />
        </Form.Item>
      );
    },
  },
  {
    name: '是否申报',
    code: 'openOrClose',
    align: 'center',
    width: 90,
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`openOrClose@${row.id}`}>
          <TjSlideSelect
            items={[
              { label: '是', value: true },
              { label: '否', value: false },
            ]}
          />
        </Form.Item>
      );
    },
  },
];

const XjAddModalContent: React.FC<IXjAddModalContentProps> = (props) => {
  const [form] = useForm();
  const [dataSource, setDataSource] = useState<any[]>([]);

  const onValuesChange = (changedValues: any, values: any) => {
    const newDataSource = _.cloneDeep(dataSource);
    const { resetKey, tableData } = changeTradeTypeFn(changedValues, newDataSource);
    if (resetKey) {
      setDataSource(tableData);
      const data: any = {};
      data[resetKey] = 0;
      form.setFieldsValue(data);
    }
  };

  useEffect(() => {
    if (props.templateData && props.templateData.length > 0) {
      const arr = _.cloneDeep(props.templateData);
      const formData: any = {};
      const notChange = ['virtualTimeOrder', 'timeOrder', 'endTime'];
      for (let i = 0; i < arr.length; i++) {
        arr[i].id = i;
        for (const key in arr[i]) {
          if (!notChange.includes(key)) {
            if (key === 'startTime' || key === 'endTime') {
              formData[`times@${i}`] = [
                moment(arr[i].startTime, 'HH:mm'),
                moment(arr[i].endTime, 'HH:mm'),
              ];
            } else {
              formData[`${key}@${i}`] = arr[i][key];
            }
          }
        }
      }
      setDataSource(arr);
      const { stationId } = props.filterValues;
      form.setFieldsValue({ ...formData, stationId, startDate: moment().add(2, 'day') });
    }
  }, [props.templateData]);

  useEffect(() => {
    props.getHandler &&
      props.getHandler(() => {
        return new Promise((resolve, reject) => {
          form
            .validateFields()
            .then((values: any) => {
              const format = {
                times: (data: any) => {
                  return {
                    startTime: data[0].format('HH:mm'),
                    endTime: data[1].format('HH:mm'),
                  };
                },
              };

              const dataList = formDataToArr({ ...values }, dataSource, 'id', undefined, format);
              const { stationId, marketId } = props.filterValues;
              const params = {
                stationId,
                marketId,
                dataList,
                startDate: moment(values.startDate).format('YYYY-MM-DD'),
                endDate: moment(values.startDate).endOf('month').format('YYYY-MM-DD'),
              };

              saveDailyRollingTradeReport(params)
                .then((res: any) => {
                  if (res.statusCode === HttpCode.SUCCESS) {
                    message.success('新增成功');
                    resolve('');
                  } else {
                    message.error(res.message);
                    reject();
                  }
                })
                .catch(() => {
                  reject();
                });
            })
            .catch((values: any) => {
              reject(values);
            });
        });
      });
  });

  return (
    <div className="xj-add-modal-content">
      <TjForm
        form={form}
        items={[
          {
            label: '日期',
            name: 'startDate',
            render: <SingleRangePicker />,
          },
          {
            label: '交易单元',
            name: 'stationId',
            render: (
              <Select disabled>
                {props.stationsOptions.map((item) => (
                  <Select.Option key={item.stationId} value={item.stationId}>
                    {item.stationName}
                  </Select.Option>
                ))}
              </Select>
            ),
          },
          {
            name: 'dataList',
            render: (
              <div className="table-box">
                <TjTable columns={columns} dataSource={dataSource} primaryKey={'id'} />
              </div>
            ),
            wrapperCol: { span: 24 },
          },
        ]}
        onValuesChange={onValuesChange}
      />
    </div>
  );
};

interface IXjAddModalContentProps {
  templateData: any[];
  filterValues: any;
  stationsOptions: any[];
  getHandler?: (fn: () => Promise<any>) => void;
}

export default XjAddModalContent;
